<?php

namespace app\controllers;

use app\models\Users;
use Yii;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        $session=Yii::$app->session;
        $view=Yii::$app->view;

        if(isset($session["username"])){
            $username=$session["username"];
            $view->params["username"]=$username;
        }

        $lost=(new Query())
            ->select(["id","place","time","name","class","publish_time","img_url"])
            ->from("find")
//            ->where(["able"=>1])
            ->orderBy("publish_time desc")
            ->all();

        $lost_len=count($lost);

        $find=(new Query())
            ->select(["id","place","time","name","class","publish_time","img_url"])
            ->from("get")
//            ->where(["able"=>1])
            ->orderBy("publish_time desc")
            ->all();

        $find_len=count($find);
        //对丢失的数据加一个属性，名为 add_type=lost,
        foreach ($lost as &$value){
            $value["add_type"]="丢";
        }
        //对捡到的数据加一个属性，名为 add_type=lost,
        foreach($find as &$value){
            $value["add_type"]="寻";
        }


        $total=array_merge($lost,$find);

        usort($total,function($a,$b){
            if ($a["publish_time"]<$b["publish_time"]){
                return 1;
            }else{
                return -1;
            }
        });

        return $this->render('index',["total"=>$total]);
    }

//    登录失败返回1,登录成功跳到到主页面
    public function actionSignin()
    {
        $request=Yii::$app->request;
        $session=Yii::$app->session;
        if ($request->isPost){
            $username=$request->post("username");
            $password=$request->post("password");
            $result=Users::find()->where(["username"=>$username,"password"=>md5($password)])->all();
            if($result){
                $session["username"]=$username;
                return $this->redirect("?r=site/index");
            }else{
                return $this->render("signin",["ret_in_mes"=>1]);
            }
        }
        return $this->render("signin");
    }

//    注册成功返回101 ，注册失败返回102
    public function actionSignup()
    {
        $request=Yii::$app->request;
        if ($request->isPost){
            $username=$request->post("username");
            $password=$request->post("password");
            $email=$request->post("email");
            $result_name=Users::find()->where(["username"=>$username])->all();
            $result_email=Users::find()->where(["email"=>$email])->all();
            if (!$result_name&&!$result_email){
//                学号和email都不重合
                $new_user=new Users();
                $new_user->username=$username;
                $new_user->password=md5($password);
                $new_user->email=$email;
                if ($new_user->save()){
                    return $this->render("signin",["ret_up_mes"=>101]);
                }else
                    die("error");
            }else{
                return $this->render("signin",["ret_up_mes"=>102]);
            }
        }
        return $this->render("signin");
    }


    /**
     * Login action.
     *
     * @return string
     */

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

}
